import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import {ElMessage} from "element-plus";

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    redirect:'/user',
    children:[
      {path: '/user', component: () => import('../views/user/UserView.vue'),meta: { requiresAuth: true }},
      {path: '/vehicle', component: () => import('../views/vehicle/VehicleView.vue'),meta: { requiresAuth: true }},
      {path: '/application', component: () => import('../views/schedule/ApplicationView.vue'),meta: { requiresAuth: true }},
      {path: '/audit', component: () => import('../views/schedule/AuditView.vue'),meta: { requiresAuth: true }},
      {path: '/distribute', component: () => import('../views/schedule/DistributeView.vue'),meta: { requiresAuth: true }},
      {path:'/geofence',component:()=>import('../views/geofence/GeofenceView.vue'),meta: { requiresAuth: true }},
      {path:'/geofenceMap',component:()=>import('../views/geofence/GeofenceMapView.vue'),meta: { requiresAuth: true }},
      {path:'/dict',component:()=>import('../views/dictionary/DictView.vue'),meta: { requiresAuth: true }},
      {path:'/dictOption',component:()=>import('../views/dictionary/DictOptionView.vue'),meta: { requiresAuth: true }},
    ]
  },
  {path: '/login', component: () => import('../views/LoginView.vue')}
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 全局前置守卫：登录拦截 本地没有存用户数据,请重新登录
/*router.beforeEach 方法在每次路由切换前执行检查。检查目标路由是否有 requiresAuth 属性。
如果有且用户未登录，则重定向到登录页面。否则，允许访问目标路由。*/
router.beforeEach((to, from, next) => {
  const user = getUser();
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!user.username) {
      ElMessage.info('请先登录')
      next({ path: '/login' });
    } else {
      next();
    }
  } else {
    next();
  }
});

function getUser() {
  const userStr = localStorage.getItem('user');
  return userStr ? JSON.parse(userStr) : { username: '' };
}

export default router
